/**
 * list组件啊；
 * 1.组件渲染
 * 2.事件绑定
 * 3.事件处理[具体事件处理设置为私有]
 *   事件处理函数中包含了数据处理
 */
import { IListOptions, ITodoData } from "../typings";
import Component from "./Component";

class List extends Component{
  private wrapperEl: HTMLElement
  private static todoData: ITodoData[]

  constructor(options: IListOptions) {
    super()
    this.wrapperEl = options.wrapperEl
    List.todoData = options.todoData
  }

  /**
   * 组件渲染函数render
   */
  public render() {
    this.wrapperEl.innerHTML += Component.listView(List.todoData)
  }

  /**
   * 事件绑定函数bindEvent
   */
  public bindEvent() {
    const oTodoList: HTMLElement = document.querySelector('.todo-list')
    oTodoList.addEventListener('click', this.handleListClick.bind(this), false)
  }

  /**
   * 
   * @param e 监听那一个事件触发了
   */
  private handleListClick(e: MouseEvent) {
    const tar = e.target as HTMLElement
    const tagName = tar.tagName.toLowerCase()
    const oTodoItems: HTMLCollection = document.getElementsByClassName('todo-item');

    if('input' === tagName || 'button' === tagName) {
      const _id: number = parseInt(tar.dataset.id)
      switch(tagName) {
        case 'input':
          this._handleCheckedBoxClick(_id, oTodoItems)
          break
        case 'button':
          this._handleBtnClick(_id, oTodoItems)
          break
        default:
          break
      }
    }
  }

  /**
   * 复选框组件的点击事件
   * @param id 
   * @param oTodoItems 
   */
  private _handleCheckedBoxClick(id: number, oTodoItems: HTMLCollection) {
    List.todoData = List.todoData.map((todo: ITodoData, index: number) => {
      if(todo.id === id) {
        todo.completed = !todo.completed
        oTodoItems[index].querySelector('span').style.textDecoration = todo.completed ? 'line-through' : ''
      }
      return todo
    })
  }

  /**
   * 删除按钮事件的处理
   * @param id 
   * @param oTodoItems 
   */
  private _handleBtnClick(id: number, oTodoItems: HTMLCollection) {
    List.todoData = List.todoData.filter((todo: ITodoData, index: number) => {
      if(todo.id !== id) {
        return todo
      }else {
        oTodoItems[index].remove()
      }
    })
  }

  /**
   * 组件项添加:本应该是在input组件中，但是数据处理在List组件中
   */
  public static addItem(val: string) {
    const oTodoList: HTMLElement = document.querySelector('.todo-list')
    const _item = {
      id: new Date().getTime(),
      content: val,
      completed: false
    }
    const _todo = List.todoData.find((td) => td.content === val)
    if(_todo) {
      alert('已添加...')
      return
    }
    List.todoData.push(_item)
    if(List.todoData.length === 1) {
      oTodoList.innerHTML = ''
    }
    oTodoList.innerHTML += Component.todoView(_item)
  }
}

export default List